package com.xjw.test;

import java.io.File;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;

/**      
 * 项目名称：springMvc  
 * 实现功能：  
 * 类名称：Searcher   
 * 类描述：(该类的主要功能)
 * 创建人：徐纪伟 
 * E-mail: xujiwei558@126.com
 * 创建时间：Feb 8, 2014 5:19:17 PM   
 * 修改人：   
 * 修改时间：   
 * 修改备注：   
 * @version    
 */
public class Searcher {
	private File indexDir;//索引文件目录
	private String fieldName;//索引段名称
	
	public Searcher(){

	}
	
	public Searcher(String IndexDir,String fieldName){
		this.indexDir = new File(IndexDir); 
		this.fieldName = fieldName;
	}
	

	@Test
	public void main() {
		Searcher searcher = new Searcher("F:\\开发\\java\\lucene\\index","content");
		try {
			searcher.search("123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询
	 * @param indexDir
	 * @param q
	 * @throws Exception
	 * @author lm
	 */
	@SuppressWarnings("deprecation")
	public void search(String keywords) throws Exception {
		
		//①　打开索引
        Directory fsDir = FSDirectory.open(indexDir);
        IndexReader reader = IndexReader.open(fsDir);
        IndexSearcher is = new IndexSearcher(reader);
        
        //② 分析查询  fieldName：索引创建时的field名称
        // Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
        QueryParser queryParser = new QueryParser(Version.LUCENE_46, fieldName, analyzer);
        Query query = queryParser.parse(keywords);
        
        //③ 搜索索引
        TopDocs docs =is.search(query, 6);
        
        // ④ 得到匹配的文档
        ScoreDoc[] scoreDoc = docs.scoreDocs;
        System.err.println("Found " + docs.totalHits + " document(s) that matched query '" + keywords + "'.");
        for (int i = 0; i < scoreDoc.length; i++) {
        	Document midDoc = reader.document(scoreDoc[i].doc);
            System.out.println(midDoc.get(fieldName));
        }
        
        reader.close();
        
    }


}
